import { Component } from "react";
import NavHeader from "../../components/NavHeader";
import { Toast } from "antd-mobile";

import { withFormik, Form, Field, ErrorMessage } from 'formik'

import * as Yup from 'yup'

import styles from './index.module.css'

import { API } from "../../utils/api";

class Login extends Component {
  render() {
    // 通过props获取高阶组件传递的属性
    // const { values, handleSubmit, handleChange, handleBlur, errors, touched } = this.props
    const { handleSubmit } = this.props

    return (
      <div className={styles.login}>
        <NavHeader>账号登录</NavHeader>
        <Form>
          <Field
            name="username"
            placeholder="请输入账号"
            className={styles.inputItem}
          />
          <ErrorMessage className={styles.errorMsg} name="username" component="div"></ErrorMessage>
          <Field
            type="password"
            name="password"
            placeholder="请输入密码"
            className={styles.inputItem}
          />
          <ErrorMessage className={styles.errorMsg} name="password" component="div"></ErrorMessage>
          <div className={styles.button}>
            <div className={styles.registerButton} onClick={() => {this.props.history.push('/register')}}>
              注册
            </div>
            <button className={styles.loginButton} type="button"  onClick={() => {handleSubmit()}}>
              登录
            </button>
          </div>
        </Form>
      </div>
    )
  }
}

export default withFormik({
  // 提供状态
  mapPropsToValues: () => ({username: '', password: ''}),
  // 添加表单校验规则
  validationSchema: Yup.object().shape({
    username: Yup.string().required('账号为必填项！').matches(/^[\w]{5,8}$/, '长度为5-8位，只能包含数字、字母、下划线'),
    password: Yup.string().required('密码为必填项！').matches(/^[\w]{5,12}$/, '长度为5-12位，只能包含数字、字母、下划线'),
  }),
  // 表单提交事件
  handleSubmit: async (values, { props }) => {
    const { username, password } = values
    let res = await API.post('/user/login', {
      username,
      password
    })
    if (res.data.status === 200) {
      localStorage.setItem('hkzf_token', JSON.stringify(res.data.body))
      if (props.location.state) {
        console.log(props.location.state.from.pathname);
        props.history.replace(props.location.state.from.pathname)
      } else {
        props.history.go(-1)
      }
    } else {
      Toast.fail(`错误：${res.data.description}`, 1)
    }
  }
})(Login)